package cn.fx.framework.utils;

/**
 * 主要实现IPV4与long的转换，便于数据存储与比较
 * @author fhb
 */
public class IpUtils {

    /**
     * 将字符串ipv4转换成long
     * 当返回0L，表示出错了
     *
     * @param strIpv4
     * @return
     */
    public static long ipv4ToLong(String strIpv4) {
        long result = 0L;
        String[] arrIp = strIpv4.split("\\.");
        if (arrIp.length == 4) {
            for (int i = 0; i < arrIp.length; i++) {
                long longSlice = Long.parseLong(arrIp[i]);
                if (longSlice > 255) {
                    result = 0L;
                    break;
                }
                longSlice = longSlice << (3 - i) * 8;

                result = result | longSlice;
            }
        }
        return result;
    }

    /**
     * 将ipv4的long值转换成字符串Ipv4
     * 返回空串，表示出错了，通常为数值太大
     * @param longIpv4
     * @return
     */
    public static String longToIpv4(long longIpv4) {
        StringBuilder sb = new StringBuilder();
        if (longIpv4 < 4294967295L) {
            long longSlice = 0;
            for (int i = 3; i >= 0; i--) {
                longSlice = (longIpv4 & (255 << i * 8)) >>> i * 8;
                sb.append(longSlice);
                if (i != 0) {
                    sb.append(".");
                }
            }
        }
        return sb.toString();
    }
}
